<?php

if (X::cfg('access:cache_time') > 0) {
    $ct = X::cfg('access:cache_time');
    $cd = X::cfg('access:cache_dir');
    $cn = session_id().md5($_SERVER['REQUEST_URI']);
    X::notice('starting cache handlers for '.$cn);

    if (time() - X::cfg('access:cache_last_drop') > X::cfg('access:cache_drop_interval')) {
        // dropping cache
        FSTools::unlink($cd.'/*');
        X::cfg_set('access:cache_last_drop', time());
        X::cfg('access')->save();
        X::notice('cache dropped.');
    }

    if ((abs(time() - filemtime($cd.$cn)) < $ct) && (file_exists($cd.$cn))) {
        X::notice('cache for '.$cn.' is actual. Dying...');
        die(file_get_contents($cd.$cn));
    } else {
        X::notice('cache for '.$cn.' is not actual. Updating...');
        ob_start('ob_h');
    }
} elseif (X::cfg('access:gzip_level') > 0) {
    X::notice('Caching disabled. Gzipping only.');
    ob_start('gzip');
}

function ob_h($data) {
//    if (stristr($hs, $needle))
    $hs = headers_list();
    $text = false;
    foreach($hs as $h) {
        if (preg_match('/^Content-Type:\s*text/i', $h)) {
            $text = true;
        }
    }
    if (!$text) return $data;
    $data = trim($data);
    $ct = X::cfg('access:cache_time');
    $cd = X::cfg('access:cache_dir');
    $cn = session_id().md5($_SERVER['REQUEST_URI']);
    header('X-cache-id: '.$cn);
    $data = update_cache($cd.$cn, $data);
    return $data;
}

function compress($data) {
    if (X::cfg('access:gzip_level') > 0) {
        if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') > -1) {
            $data = gzdeflate($data, X::cfg('access:gzip_level'));
            header('Content-Encoding: deflate');
        } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') > -1) {
            $data = gzencode($data, X::cfg('access:gzip_level'));
            header('Content-Encoding: gzip');
        }
    }
    return $data;
}

function update_cache($cn, $data) {
    $data = compress($data);
    file_put_contents($cn, $data);

    return $data;
}
?>
